package com.shujia.liaotian;


import com.shujia.liaotian.bean.Message;
import com.shujia.liaotian.bean.User;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;

public class Server {

    //所有上线用户列表
    private static HashMap<String, User> loginList = new HashMap<String, User>();

    public static Integer flaglength = 0;

    /**
     * 客户端上线方法   相当于登录   建立连接
     */
    public static void main(String[] args) throws Exception {

        login();

    }


    static void login() {
        try {
            ServerSocket serverSocket = new ServerSocket(8000);
            while (true) {

                //监听客户端的请求

                Socket socket = serverSocket.accept();
                ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
                User user = (User) objectInputStream.readObject();

                //生成唯一标识
                user.setId(UUID.randomUUID().toString());
                user.setIp(socket.getInetAddress().getHostAddress());
                loginList.put(user.getId(), user);

                flaglength++;

                //启动一个线程负责更新新上线用户列表  为每一个客户端都会启动一个线程
                new UserListUpdateThread(socket, loginList).start();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


class UserListUpdateThread extends Thread {
    private Socket socket;
    private HashMap<String, User> loginList;
    private Integer flag = 0;


    public UserListUpdateThread(Socket socket, HashMap<String, User> loginList) {
        this.socket = socket;
        this.loginList = loginList;
    }


    @Override
    public void run() {
        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            //监听loginList 长度  如果长度改变说明有用户上线或者下线
            while (true) {
                //判断是否有新的客户端上线
                if (Server.flaglength > flag) {
                    ArrayList<User> users = new ArrayList<>();
                    for (User user : loginList.values()) {

                        user.setPassword("");
                        users.add(user);
                    }

                    objectOutputStream.writeObject(users);
                    objectOutputStream.flush();

                    flag = Server.flaglength;
                } else {

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
